/*
 * Copyright (C), 2002-2015, 苏宁易购电子商务有限公司
 * FileName: UserManagementAction.java
 * Author:   admin
 * Date:     2015年12月29日 上午9:14:15
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.app.snpaasadmin.action;

import com.opensymphony.xwork2.ActionSupport;
import com.suning.app.snpaasadmin.api.OauthApi;
import com.suning.app.snpaasadmin.api.UserApi;
import com.suning.app.snpaasadmin.domain.AppEnvInfo;
import com.suning.app.snpaasadmin.domain.OauthToken;
import com.suning.app.snpaasadmin.domain.ServiceBoughtList;
import com.suning.app.snpaasadmin.domain.UserInfo;
import com.suning.app.snpaasadmin.domain.UserOverview;
import com.suning.app.snpaasadmin.domain.UserRecordLog;
import com.suning.app.snpaasadmin.operation.CfClusterDBOperation;
import com.suning.app.snpaasadmin.operation.UserManagementDBOperation;
import com.suning.app.snpaasadmin.pojo.AppEnvironment;
import com.suning.app.snpaasadmin.pojo.CfApp;
import com.suning.app.snpaasadmin.pojo.CfCluster;
import com.suning.app.snpaasadmin.pojo.CfServiceBought;
import com.suning.app.snpaasadmin.pojo.CfUserRecord;
import com.suning.app.snpaasadmin.util.Constants;
import com.suning.app.snpaasadmin.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * 用户总览<br>
 * 〈功能详细描述〉
 *
 * @author admin
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
public class UserManagementAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    
    private Logger logger = Logger.getLogger(UserManagementAction.class);
    
    private Map<String, Object> dataMap;

    @Autowired
    private UserManagementDBOperation umDBOper;

    private Integer page;

    private String userId;

    private String appId;

    private String deployId;

    @Autowired
    private CfClusterDBOperation clusterDB;

    /**
     * 
     * 功能描述: <br>
     * 用户总览
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String getUserList() throws Exception {
        dataMap = new HashMap<String, Object>();
        List<UserInfo> envList = umDBOper.getAppList();
        UserOverview overview = new UserOverview();
        overview.setUser(envList);
        overview.setPageCount(
                envList.size() / Constants.PAGE_SIZE + ((envList.size() % Constants.PAGE_SIZE == 0) ? 0 : 1));
        overview.setPageNow(page);
        
        // 查询出用户总的应用数和服务数
        dataMap.put("data", overview);
        dataMap.put("success", true);
        return SUCCESS;
    }

    public String getUserDetail() throws Exception {
        dataMap = new HashMap<String, Object>();
        List<ServiceBoughtList> sbList = new ArrayList<>();
        // 根据userId查询

        // 先获取环境
        List<AppEnvironment> environments = umDBOper.getUserAllEnv(userId);
        logger.fatal("userId:"+userId);
        List<AppEnvInfo> appEnvInfos = new ArrayList<>();
        Map<String, Object> result = new HashMap<>();
        if (environments != null && environments.size() > 0) {

            // 循环遍历
            for (AppEnvironment env : environments) {
                AppEnvInfo envInfo = new AppEnvInfo();
                envInfo.setStatus(Constants.STATUS_ENV_UNUSE);
                
                // 根据envId查询出app和服务
                Integer envId = env.getId();
                List<CfApp> apps = umDBOper.getAppEnv(envId);
                if (apps != null && apps.size() > 0) {
                    envInfo.setAppId(apps.get(0).getId());
                    envInfo.setAppName(apps.get(0).getAppName());
                    envInfo.setSourcecode(apps.get(0).getGiturl());
                    
                    //查询所有集群的域名
                    List<CfCluster> clusters = clusterDB.getCfClusterAll(null);
                    if(clusters != null && clusters.size() > 0) {
                        if(StringUtil.isNotEmpty(env.getDomain()) && StringUtil.isNotNullString(env.getDomain())) {
                            String domain = env.getDomain().substring(env.getDomain().indexOf(".")+1);
                            for(CfCluster cfCluster : clusters) {
                                if(cfCluster.getRootDomain().equals(domain)) {
                                    envInfo.setDeployId(cfCluster.getId().toString());
                                    
                                    //判断应用的状态
                                    OauthToken token = OauthApi.login(Constants.BROKER_AUTH_USERNAME, Constants.BROKER_AUTH_PASSWORD,
                                            cfCluster.getRootDomain());
                                    Map<String, Object> appCl = UserApi.getApp(cfCluster.getRootDomain(), apps.get(0).getUuid(), token);
                                    if ((Integer.valueOf(appCl.get("running_instances").toString()).equals(Constants.CLUSTER_UNDEPLOY))) {
                                        envInfo.setStatus(Constants.STATUS_ENV_STOP);
                                    } else {
                                        envInfo.setStatus(Constants.STATUS_ENV_START);
                                    }
                                }
                            }
                        }
                    }
                }
                envInfo.setDisk(env.getDisk());
                envInfo.setDomain(env.getDomain());
                envInfo.setEnvId(envId);
                envInfo.setEnvName(env.getEnvName());
                envInfo.setInstance(env.getInstance());
                envInfo.setMemory(env.getMemory());
                
                Long endTime = 0L;
                //查询环境到期时间
                Map<String, String> res = UserApi.getServiceStatus(env.getInstanceId(), userId, 0);
                if (res.get("endDate") != null ) {
                    String endDate = res.get("endDate").toString();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    endTime = sdf.parse(endDate).getTime();
                    envInfo.setEndTime(endTime);
                }
                // 获取sdk和runtime
                envInfo.setSdk(umDBOper.getSdkName(env.getSdkId()));
                envInfo.setRuntime(umDBOper.getRuntime(env.getRuntimeId()));

                // 获取环境下的服务图片
                if (umDBOper.getServiceImg(envId) != null) {
                    envInfo.setService(umDBOper.getServiceImg(envId));
                }

                List<CfServiceBought> services = umDBOper.getServiceBoughts(envId, Long.valueOf(userId));
                if (services != null && services.size() > 0) {

                    for (CfServiceBought serviceBought : services) {
                        ServiceBoughtList boughtList = new ServiceBoughtList();
                        boughtList.setEndTime(endTime);
                        boughtList.setName(serviceBought.getBoughtServiceName());
                        boughtList.setEnvName(env.getEnvName());
                        sbList.add(boughtList);
                    }
                }
                appEnvInfos.add(envInfo);
            }
            

            // 获取用户的操作记录(根据userId)
            List<CfUserRecord> userRecords = umDBOper.getUserRecordLog(userId);
            List<UserRecordLog> logs = new ArrayList<>();
            if (userRecords != null && userRecords.size() > 0) {
                for (CfUserRecord record : userRecords) {
                    String paramRes = "{";
                    UserRecordLog recordLog = new UserRecordLog();
                    recordLog.setUrl(record.getAction());
                    recordLog.setTime(record.getCreateTime().getTime());
                    if (StringUtil.isEmpty(record.getParams()) || StringUtil.isNullString(record.getParams())) {
                        logs.add(recordLog);
                    } else {
                        String[] params = record.getParams().split("&");
                        for (String tmp : params) {
                            if (tmp.indexOf("noCache") > -1) {
                                continue;
                            }
                            paramRes = paramRes + tmp + ",";
                        }
                        if ("{".equals(paramRes)) {
                            logs.add(recordLog);
                        } else {
                            paramRes = paramRes.substring(0, paramRes.lastIndexOf(","));
                            paramRes = paramRes + "}";
                            recordLog.setParams(paramRes);
                            logs.add(recordLog);
                        }
                    }
                }
            }
            result.put("log", logs);
            result.put("envList", appEnvInfos);
            result.put("service", sbList);
        }
        dataMap.put("data", result);
        dataMap.put("success", true);
        return SUCCESS;
    }

    public String startApp() throws Exception {
        dataMap = new HashMap<String, Object>();
        // 获得当前集群的域名
        //CfCluster cfCluster = clusterDB.selectCfCluster(deployId);

        // 根据当前appId获取uuid
        CfApp app = umDBOper.getOneApp(appId);
        OauthToken token = OauthApi.login(Constants.BROKER_AUTH_USERNAME, Constants.BROKER_AUTH_PASSWORD,
                "jiawei.zhou");
        UserApi.startApplication("jiawei.zhou", app.getUuid(), token);
        Integer appState = 1;
        while (appState == 1) {
            Map<String, Object> appCl = UserApi.getApp("jiawei.zhou", app.getUuid(), token);
            if ((Integer.valueOf(appCl.get("running_instances").toString()).equals(0))) {
                appState = 1;
            } else {
                appState = 2;
            }
            Thread.sleep(1000);
        }
        dataMap.put("success", true);
        return SUCCESS;
    }

    public String stopApp() throws Exception {
        dataMap = new HashMap<String, Object>();
        // 获得当前集群的域名
        //CfCluster cfCluster = clusterDB.selectCfCluster(deployId);

        // 根据当前appId获取uuid
        CfApp app = umDBOper.getOneApp(appId);
        
        OauthToken token = OauthApi.login(Constants.BROKER_AUTH_USERNAME, Constants.BROKER_AUTH_PASSWORD,
                "jiawei.zhou");
        UserApi.stopApplication("jiawei.zhou", app.getUuid(), token);
        Integer appState = 2;
        while (appState == 2) {
            Map<String, Object> appCl = UserApi.getApp("jiawei.zhou", app.getUuid(), token);
            if ((Integer.valueOf(appCl.get("running_instances").toString()).equals(0))) {
                appState = 1;
            } else {
                appState = 2;
            }
            Thread.sleep(1000);
        }
        dataMap.put("success", true);
        return SUCCESS;
    }

    public String restartApp() throws Exception {
        dataMap = new HashMap<String, Object>();
        // 获得当前集群的域名
        //CfCluster cfCluster = clusterDB.selectCfCluster(deployId);

        // 根据当前appId获取uuid
        CfApp app = umDBOper.getOneApp(appId);
        OauthToken token = OauthApi.login(Constants.BROKER_AUTH_USERNAME, Constants.BROKER_AUTH_PASSWORD,
                "jiawei.zhou");
        UserApi.restartApplication("jiawei.zhou", app.getUuid(), token);
        Integer appState = 1;
        while (appState == 1) {
            Map<String, Object> appCl = UserApi.getApp("jiawei.zhou", app.getUuid(), token);
            if ((Integer.valueOf(appCl.get("running_instances").toString()).equals(0))) {
                appState = 1;
            } else {
                appState = 2;
            }
            Thread.sleep(1000);
        }
        dataMap.put("success", true);
        return SUCCESS;
    }

    /**
     * @return the page
     */
    public Integer getPage() {
        return page;
    }

    /**
     * @param page the page to set
     */
    public void setPage(Integer page) {
        this.page = page;
    }

    /**
     * @return the dataMap
     */
    public Map<String, Object> getDataMap() {
        return dataMap;
    }

    /**
     * @param dataMap the dataMap to set
     */
    public void setDataMap(Map<String, Object> dataMap) {
        this.dataMap = dataMap;
    }

    /**
     * @return the userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the appId
     */
    public String getAppId() {
        return appId;
    }

    /**
     * @param appId the appId to set
     */
    public void setAppId(String appId) {
        this.appId = appId;
    }

    /**
     * @return the deployId
     */
    public String getDeployId() {
        return deployId;
    }

    /**
     * @param deployId the deployId to set
     */
    public void setDeployId(String deployId) {
        this.deployId = deployId;
    }

}